package com.nsyue.auth.controller.result;

import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Optional;

@Data
@Accessors(chain = true)
public class Result<T> implements Serializable {

    /**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	/**
     * 业务错误码
     */
    private long code;
    /**
     * 结果集
     */
    private T data;
    /**
     * 描述
     */
    private String msg;

    public Result() {
        // to do nothing
    }

    public Result(IStatus errorCode) {
        errorCode = Optional.ofNullable(errorCode).orElse(ApiStatusEnum.FAILED);
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
    }

    public static <T> Result<T> ok(T data) {
        ApiStatusEnum aec = ApiStatusEnum.SUCCESS;
        if (data instanceof Boolean && Boolean.FALSE.equals(data)) {
            aec = ApiStatusEnum.FAILED;
        }
        return restResult(data, aec);
    }

    public static <T> Result<T> failed(String msg) {
        return restResult(null, ApiStatusEnum.FAILED.getCode(), msg);
    }

    public static <T> Result<T> failed(long code, String msg) {
        return restResult(null, code, msg);
    }

    public static <T> Result<T> failed(IStatus errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> Result<T> restResult(T data, IStatus errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMsg());
    }

    private static <T> Result<T> restResult(T data, long code, String msg) {
        Result<T> apiResult = new Result<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public static <T> Result<T> ok() {
        return ok(null);
    }

}
